import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_android/in_app_purchase_android.dart';

import '../controller.dart';

/// 商品列表组件
/// 作用：展示可购买的商品列表，处理购买按钮点击事件
class ProductList extends GetView<PaymentController> {
  const ProductList({super.key, required this.controller});

  final PaymentController controller;

  @override
  Widget build(BuildContext context) {
    // 加载中状态
    if (controller.state.loading.value) {
      return const Card(
          child: ListTile(
              leading: CircularProgressIndicator(),
              title: Text('Fetching products...')));
    }

    // 内购服务不可用时不展示商品列表
    if (!controller.state.isAvailable.value) {
      return const Card();
    }

    // 商品列表头部
    const ListTile productHeader = ListTile(title: Text('Products for Sale'));
    final List<ListTile> productList = <ListTile>[];

    // 展示未找到的商品ID
    if (controller.state.notFoundIds.isNotEmpty) {
      productList.add(ListTile(
          title: Text('[${controller.state.notFoundIds.join(", ")}] not found',
              style: TextStyle(color: ThemeData.light().colorScheme.error)),
          subtitle: const Text(
              'This app needs special configuration to run. Please see example README.md for instructions.')));
    }

    // 构建已购买商品的映射表（用于判断商品是否已购买）
    final Map<String, PurchaseDetails> purchases =
        Map<String, PurchaseDetails>.fromEntries(
            controller.state.purchases.map((PurchaseDetails purchase) {
      // 完成未完成的购买
      if (purchase.pendingCompletePurchase) {
        InAppPurchase.instance.completePurchase(purchase);
      }
      return MapEntry<String, PurchaseDetails>(purchase.productID, purchase);
    }));

    // 构建商品列表项
    productList.addAll(controller.state.products.map(
      (ProductDetails productDetails) {
        // 检查当前商品是否已购买
        final PurchaseDetails? previousPurchase = purchases[productDetails.id];
        
        return ListTile(
          title: Text(productDetails.title),
          subtitle: Text(productDetails.description),
          trailing: previousPurchase != null && Platform.isIOS
              ? // iOS平台：已购买商品显示升级按钮
              IconButton(
                  onPressed: () => controller.confirmPriceChange(),
                  icon: const Icon(Icons.upgrade))
              : // 未购买商品显示购买按钮
              TextButton(
                  style: TextButton.styleFrom(
                    backgroundColor: Colors.green[800],
                    foregroundColor: Colors.white,
                  ),
                  onPressed: () => controller.buyProduct(productDetails),
                  child: Text(productDetails.price),
                ),
        );
      },
    ));

    return Card(
        child: Column(
            children: <Widget>[productHeader, const Divider()] + productList));
  }
}
    